package com.ado.abyss.core.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ado.abyss.core.constants.LogEnum;
import com.ado.abyss.core.dal.model.SysDept;
import com.ado.abyss.core.manager.SysDeptManager;
import com.ado.abyss.core.service.SysDeptService;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author adonais
 * @date 2020/06/08
 * @description 机构业务接口实现
 *
 */
@Slf4j
@Service(value = "sysDeptService")
public class SysDeptServiceImpl implements SysDeptService{

	//定义日志
	private static final Logger log = LoggerFactory.getLogger(SysDeptServiceImpl.class) ;

	@Autowired
	@Qualifier(value = "sysDeptManager")
	private SysDeptManager sysDeptManager ;

	@Override
	public List<SysDept> findTree() {
		List<SysDept> sysDepts = new ArrayList<>();
		List<SysDept> depts = sysDeptManager.findAll();
		for (SysDept dept : depts) {
			if (dept.getParentId() == null || dept.getParentId() == 0) {
				dept.setLevel(0);
				sysDepts.add(dept);
			}
		}
		findChildren(sysDepts, depts);
		log.info("{} : {}" , LogEnum.DEPT_MODULE , "查询结果:" + sysDepts.toString());
		return sysDepts;
	}

	private void findChildren(List<SysDept> sysDepts, List<SysDept> depts) {
		for (SysDept sysDept : sysDepts) {
			List<SysDept> children = new ArrayList<>();
			for (SysDept dept : depts) {
				if (sysDept.getId() != null && sysDept.getId().equals(dept.getParentId())) {
					dept.setParentName(dept.getName());
					dept.setLevel(sysDept.getLevel() + 1);
					children.add(dept);
				}
			}
			sysDept.setChildren(children);
			findChildren(children, depts);
		}
	}

	@Override
	public boolean save(SysDept record) {
		boolean flag = sysDeptManager.saveDept(record) ;
		return flag;
	}

	@Override
	public boolean delete(SysDept record) {
		boolean flag = sysDeptManager.deleteById(record.getId()) ;
		return flag;
	}

	@Override
	public boolean deleteBatch(List<SysDept> records) {
		boolean flag = false ;
		List<Long> list = new ArrayList<Long>();
		for (SysDept sysDept : records) {
			list.add(sysDept.getId()) ;
		}
		flag = sysDeptManager.deleteByIds(list) ;
		return flag;
	}

	@Override
	public SysDept findById(Long id) {
		SysDept sysDept = sysDeptManager.findById(id) ;
		return sysDept;
	}

}
